package breeze.library.orchid.web;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class OrchidDownloader {

    private static final String TAG = "OrchidDownloader";
    private ProgressDialog progressDialog;
    private Activity activity;
    private File targetPath = null;
    private Thread thread = null;
    private String fileLink = "";
    private onDownloading downloading = null;
    private boolean showProgressDialog = true;
    private long fileSize = -1;

    public OrchidDownloader(Activity activity, String fileLink, File targetPath, onDownloading downloading) {
        this.activity = activity;
        this.fileLink = fileLink;
        this.targetPath = targetPath;
        this.downloading = downloading;
        this.thread = new Thread(runnable);
        // 初始化進度條
        this.progressDialog = new ProgressDialog(activity);
        this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        this.progressDialog.setTitle("提示");
        this.progressDialog.setMessage("正在下载中...");
        this.progressDialog.setButton(ProgressDialog.BUTTON_POSITIVE,"取消",((dialog, which) -> this.cancel()));
    }

    public interface onDownloading {
        void onProgressChanged(int progress);

        void onSuccess(File file);

        void onError(Exception exception);
    }

    public void setProgressDialogButton(int which, String text, DialogInterface.OnClickListener listener) {
        this.progressDialog.setButton(which, text, listener);
    }

    public void download() {
        if (showProgressDialog)
            this.progressDialog.show();
        thread.start();
    }

    private final Runnable runnable = () -> {
        // download
        try {
            HttpURLConnection httpURLConnection = OrchidWebUtils.openWebConnection(fileLink, null, null);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            FileOutputStream fileOutputStream = new FileOutputStream(targetPath);
            byte[] bytes = new byte[2048];
            int length, recorded = 0;
            long totalLength = Build.VERSION.SDK_INT >= 24 ? httpURLConnection.getContentLengthLong() : httpURLConnection.getContentLength();
            if (totalLength<=0 && fileSize>0) {
                totalLength = fileSize;
            }
            while ((length = bufferedInputStream.read(bytes)) != -1) {
                recorded += length;
                if (totalLength > -1) {
                    int progress = (int) (((float) recorded / (float) totalLength) * 100);
                    downloading.onProgressChanged(progress);
                    progressDialog.setProgress(progress);
                } else {
                    downloading.onProgressChanged(-1);
                    progressDialog.setProgress(-1);
                }
                fileOutputStream.write(bytes,0,length);
                Log.d(TAG, "全部大小:"+totalLength+"|当前大小:"+length+"|记录大小:"+recorded);
            }
            fileOutputStream.close();
            bufferedInputStream.close();
            downloading.onSuccess(targetPath);
            downloading.onProgressChanged(100);
        } catch (Exception exception) {
            exception.printStackTrace();
            downloading.onError(exception);
        }
    };

    public ProgressDialog getProgressDialog() {
        return progressDialog;
    }

    public boolean isShowProgressDialog() {
        return showProgressDialog;
    }

    public void setShowProgressDialog(boolean showProgressDialog) {
        this.showProgressDialog = showProgressDialog;
    }

    public void cancel() {
        if (!thread.isInterrupted()) {
            thread.interrupt();
        }
    }

    public long getFileSize() {
        return fileSize;
    }

    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }
}
